package com.example.mobilesafe.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class AddressDao {

    // 1.指定访问数据库的路径
    public static String path = "data/data/com.example.mobilesafe/files/address.db";

    private static String mAddress;

    /**
     * 开启数据库连接，进行访问
     * @param phone 电话号码
     */
    public static String getAddress(String phone){

        mAddress = "未知号码";

        // 0.定义SQLite数据库对象
        SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);;

        // 1.对手机号码进行正则表达式处理
        String regularExpression = "^1[3-8]\\\\d{9}";
        if (phone.matches(regularExpression)){
            phone = phone.substring(0,7); // 取电话号的前7位

            // 2.数据库查询
            Cursor cursor = db.query("data1", new String[]{"outkey"}, "id = ?", new String[]{phone}, null, null, null);
            // 3.查到即可
            if (cursor.moveToNext()){
                // 4.从data1表中获取外键outkey
                String outkey = cursor.getString(0);
                // 5.从data2表中通过outkey来获取location
                Cursor indexCursor = db.query("data2", new String[]{"location"}, "id = ?", new String[]{outkey}, null, null, null);
                if (indexCursor.moveToNext()){
                    // 6.获取查询到的电话归属地
                    mAddress = indexCursor.getString(0);
                }
            }else {
                mAddress = "未知号码";
            }
        }else {
            int length = phone.length();
            switch (length){
                case 3: // 119,110,112，114
                    mAddress = "报警电话";
                    break;
                case 4:
                    mAddress = "模拟器";
                    break;
                case 5:// 10086,99555
                    mAddress = "服务电话";
                    break;
                case 7:
                    mAddress = "固定电话";
                    break;
                case 8:
                    mAddress = "固定电话";
                    break;
                case 11: // （3 + 8） 区号 + 座机号码
                    String area = phone.substring(1, 3);
                    Cursor cursor2 = db.query("data2", new String[]{"location"}, "area = ?", new String[]{area}, null, null, null);
                    if (cursor2.moveToNext()){
                        mAddress = cursor2.getString(0);
                    }else {
                        mAddress = "未知号码";
                    }
                    break;
                case 12: // （4 + 8） 区号 + 座机号码
                    String area2 = phone.substring(1, 4);
                    Cursor cursor3 = db.query("data2", new String[]{"location"}, "area = ?", new String[]{area2}, null, null, null);
                    if (cursor3.moveToNext()){
                        mAddress = cursor3.getString(0);
                    }else {
                        mAddress = "未知号码";
                    }
                    break;
            }
        }
        return mAddress;
    }
}